import paho.mqtt.client as mqtt
import json


class MqttClientSingleton:
    _instance = None

    def __new__(cls, broker_address, broker_port, client_id, username, password):
        if cls._instance is None:
            cls._instance = super(MqttClientSingleton, cls).__new__(cls)
            cls._instance._initialize_mqtt_client(broker_address, broker_port, client_id, username, password)
        return cls._instance

    def _initialize_mqtt_client(self, broker_address, broker_port, client_id, username, password):
        self.mqtt_client = mqtt.Client(client_id=client_id)
        self.mqtt_client.on_connect = self._on_connect
        self.mqtt_client.on_disconnect = self._on_disconnect
        self.mqtt_client.username_pw_set(username, password)
        self.mqtt_client.connect(broker_address, broker_port, keepalive=60)

    def _on_connect(self, client, userdata, flags, rc):
        print(f"Connection result code: {rc}")
        if rc == 0:
            print("Connected to broker")
        else:
            print("Connection failed")

    def _on_disconnect(self, client, userdata, rc):
        print(f"Disconnected. Trying to reconnect...")
        client.reconnect()

    def publish_data(self, topic, data):
        json_data = json.dumps(data)
        self.mqtt_client.publish(topic, json_data, qos=1)
